<?php

/**
 * TODO: Add loging
 *
 */

/**
 * @see Zend_Loader
 */
require_once 'Zend/Loader.php';
require_once 'Zend/Gdata.php';
require_once 'Zend/Debug.php';

/**
 * @see Zend_Gdata_ClientLogin
 */
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');

/**
 * @see Zend_Gdata_Finance
 */
Zend_Loader::loadClass('Zend_Gdata_Finance');

/**
 * @see Zend_Gdata_Finance_Extension_Symbol
 */
Zend_Loader::loadClass('Zend_Gdata_Finance_Extension_Symbol');

/**
 * Constants
 */
define (_PORTFOLIO,0);
define (_TYPE,1);
define (_TICKER,2);


/**
 * Returns a HTTP client object with the appropriate headers for communicating
 * with Google using the ClientLogin credentials supplied.
 *
 * @param  string $user The username, in e-mail address format, to authenticate
 * @param  string $pass The password for the user specified
 * @return Zend_Http_Client
 */

function getClientLoginHttpClient($user, $pass)
{
	$service = Zend_Gdata_Finance::AUTH_SERVICE_NAME;
	$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
	return $client;
}

/**
 * Display list of valid commands.
 *
 * @param  string $executable The name of the current script. This is usually av
 ailable as $argv[0].
 * @return void
 */
function displayHelp($executable)
{
	echo "Usage: php {$executable} [<username>] [<password>] " .
        "[<action>]\n";
	echo "where [action] can be list\n";
}

/**
 * Return a portfolio for a given name
 */
function findPortfolio(Zend_Gdata_Finance_PortfolioFeed $feed, $name)
{
		foreach ($feed->entries as $portfolio)
  		{
  			if ( $portfolio->title ==  $name)
  			return $portfolio;
  		}	
}

if (isset($argc) && $argc >= 4)
{
	try 
	{
		$client = getClientLoginHttpClient($argv[1], $argv[2]);
		$gdata = new Zend_Gdata_Finance($client);
		$gdata->enableRequestDebugLogging('/tmp/zend_debug.txt');
	} catch (Zend_Gdata_App_AuthException $e) {
		echo "Error: Unable to authenticate. Please check your";
		echo " credentials.\n";
		exit(1);
	}
}
else
{
	displayHelp($argv[0]);
	exit(1);
}

$feed=$gdata->getPortfolioFeed();
if ($argv[3] == "list")
{
# Iterate over the portfolio entries in the feed and display each transaction.
  foreach ($feed->entries as $portfolio)
  	{
		$positions = $gdata->getPositionFeed($portfolio->id. "/positions?transactions=true" );
			foreach ($positions->entries as $entry )
			{
				foreach ($entry->getFeedLink() as  $transactions) 
				{
					$transacFeed = $transactions->getFeed();
					foreach ($transacFeed->entries as $transaction )
					{
						echo $portfolio->title . ",";
						echo $entry->symbol->exchange . ":" . 	$entry->symbol->symbol . ",";
						echo $entry->symbol->fullName . ",";
						$tranData = $transaction->transactionData;
						echo $tranData->type. ",";
						echo $tranData->date. ",";
						echo $tranData->shares. ",";
						echo $tranData->price->getMoney()->getAmount() . "";
						echo $tranData->commission->getMoney()->getAmount() . ",";
					    echo $tranData->notes. "";
						echo "\n";
					}
				}
			}
		}
}
/* Adding transactions */
/*
 * TODO: Needs work
if ($argv[3] == "add")
{

$handle=fopen($argv[4],"r");


while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
	if ($data[_TYPE]=="type")
		continue;	

	if ($data[_TYPE]=="Buy" )
	{
		$num = count($data);
		#echo "$num fields in line $row:\n";
		//$row++;
		//for ($c=0; $c < $num; $c++) {
		//    	echo "$c=".$data[$c] . ",";
		//  /  }
		//echo "\n";
		$portfolio=findPortfolio($feed,$data[_PORTFOLIO]);
		$symbol = new Zend_Gdata_Finance_Extension_Symbol();
		$symbol->setTicker($data[_TICKER]);	
		try 
		{
			echo "Adding to " . $portfolio->title . ":" . $symbol->ticker. "\n";
			$gdata->addTransaction($portfolio,$data[_TYPE],"NASDAQ",$symbol->ticker);
		}
		catch(Zend_Gdata_App_HttpException  $e)
		{
			if ( preg_match("/No transaction exists with tid/",$e->getMessage()) )
			{
				echo "Ticker: " . $data[_TICKER] . " already exists\n";
			}
			else if (preg_match("/Some of the values submitted are not valid and have been ignored/",$e->getMessage()))
			{
				echo "Possible error with ticker symbol (maybe wrong exchange?): " . $e->getMessage() . "\n";				
			}
			else
				echo $e->getMessage() . "\n";
			
			exit;
		};
	}
}
}
*/
?>